package hasthi.tools.analyze;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FormattedTable {
    private List<String[]> values = new ArrayList<String[]>();
    private int[] maxwidths;
    
    public FormattedTable(String headers){
        String[] headerArray = headers.split("\\s+");
        maxwidths = new int[headerArray.length];
        values.add(headerArray);
        updateMax(headerArray);
    }
    
    
    public void addLine(String line){
        String[] entries = line.split("\\s+");
        if(entries.length > maxwidths.length){
            throw new RuntimeException("recevied " + line + " but headers was "+ Arrays.toString(values.get(0)));
        }
        values.add(entries);
        updateMax(entries);
    }
    
    
    
    private void updateMax(String[] strs){
        for(int i = 0;i<strs.length;i++){
            if(strs[i].length() > maxwidths[i]){
                maxwidths[i] = strs[i].length(); 
            }
        }
    }
    public String toHtml() {
        StringBuffer buf = new StringBuffer();
        buf.append("<table border=\"1\">");
        for(String[] entries:values){
            buf.append("<tr>");
            for(int i = 0;i<entries.length;i++){
                buf.append("<td>");
                buf.append(entries[i]);
                buf.append("</td>");
            }
            buf.append("</tr>");
            buf.append("\n");
        }
        buf.append("</table>");
        return buf.toString();
    }
    
    @Override
    public String toString() {
        StringBuffer buf = new StringBuffer();
        for(String[] entries:values){
            for(int i = 0;i<entries.length;i++){
                int padSize = maxwidths[i]+2 - entries[i].length();
                  for(int j = 0;j<padSize;j++){
                      buf.append(" ");
                  }
                buf.append(entries[i]);
            }
            buf.append("\n");
        }
        return buf.toString();
    }
}
